﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.IO;
using xTrackEmailer_Core.Properties;
using System.Net;

namespace xTrackEmailer_Core
{
    public class SendMail
    {
        #region Members
        SmtpClient m_Client = new SmtpClient();
        #endregion

        #region C-TOR
        public SendMail()
        {
            m_Client.EnableSsl = Settings.Default.SSL;
            m_Client.Host = Settings.Default.SMTP;
            m_Client.Port = Settings.Default.Port;
            m_Client.Timeout = Settings.Default.Timeout;
            m_Client.DeliveryMethod = SmtpDeliveryMethod.Network;
            m_Client.UseDefaultCredentials = false;
            m_Client.Credentials = new NetworkCredential(Settings.Default.User, Settings.Default.Password);
        }
        #endregion

        public Exception Send(string fromAddress, List<string> toAddresses, string subject, string body, bool isHtml, List<string> attachments)
        {
            try
            {
                MailMessage mm = new MailMessage();
                if (string.IsNullOrEmpty(fromAddress))
                    return new Exception("Nu este completata adresa de mail de pe care se trimite.");
                else if (toAddresses == null || toAddresses.Count == 0)
                    return new Exception("Nu este completat nici un destinatar.");

                mm.Body = body;
                mm.From = new MailAddress(fromAddress);
                mm.IsBodyHtml = isHtml;
                mm.Priority = MailPriority.Normal;
                mm.Subject = subject;

                foreach (string receiver in toAddresses)
                    mm.To.Add(receiver);

                if (attachments != null && attachments.Count > 0)
                    foreach (string att in attachments.Where(p => File.Exists(p)))
                    {
                        //FileInfo fi = new FileInfo(att);
                        mm.Attachments.Add(new Attachment(att));
                    }

                m_Client.Send(mm);
                return null;
            }
            catch (Exception ex)
            {
                return ex;
            }
        }
    }
}
